// pages/shopping-cart/shopping-cart.js
var util = require("../../utils/util.js");
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartInfo: [],
    cartLength: "",
    host: app.globalData.host,
    goodsInfo: {},
    allMoney: 0,
    agree: 1,
    buthidden: false,
    toView: 'cartItem',
    _url: '',
    clearShow: false,
    startX: 0, //开始坐标
    clearIndex: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.goodsId != undefined) {
      app.globalData.cartInfo = [];
      var count = 0;
      var that = this;
      var host = app.globalData.host;
      wx.request({
        url: host + '/index/goods',
        data: {
          'shop_id': app.globalData._shopId,
          'session_key': app.globalData.userInfo.sessionKey,
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          let data = res.data;
          if (data.code == 2000) {
            data.data.forEach(function (e) {
              count = parseInt(count) + parseInt(e.cartNum);
              if (e.cartNum > 0) {
                var cart = { id: e.id, cartNum: e.cartNum, unit: e.unit, title: e.title, goods_bn: e.goods_bn, pic_4: e.pic_4, goods_num: e.goods_num, price: e.price };
                app.globalData.cartInfo.push(cart);
              }
            })
            var a = 1;
            for (var j = 0; j < data.data.length; j++) {
              if (data.data[j].goods_num > data.data[j].cartNum){
                if (options.goodsId == data.data[j].id) {
                  for (var i = 0; i < app.globalData.cartInfo.length; i++) {
                    if (options.goodsId == app.globalData.cartInfo[i].id) {
                      app.changeCart(app.globalData._shopId, app.globalData.userInfo.sessionKey, options.goodsId, 1);
                      app.globalData.cartInfo[i].cartNum = parseInt(app.globalData.cartInfo[i].cartNum) + 1;
                      count = count + 1
                      a = 2;
                    }
                  }
                  if (a == 1) {
                    app.changeCart(app.globalData._shopId, app.globalData.userInfo.sessionKey, options.goodsId, 1);
                    var cart = { id: options.goodsId, cartNum: 1, unit: data.data[j].unit, title: data.data[j].title, goods_bn: data.data[j].goods_bn, pic_4: data.data[j].pic_4, goods_num: data.data[j].goods_num, price: data.data[j].price };
                    app.globalData.cartInfo.push(cart);
                    count = count + 1
                  }
                }
              } else{
                app.showToastNone('库存不足',2000);
              }
            }
            app.globalData.count = count;
            that.setData({
              goodsInfo: data.data,
              cartInfo: app.globalData.cartInfo,
              count: app.globalData.count,
              cartLength: app.globalData.cartInfo.length
            })
            that.totalMoney();
            app.globalData.goodsInfo = data.data;
          } else {
            util.showModel('获取商品失败', data.msg)
          }
        }
      })
    } else {
      this.setData({
        goodsInfo: app.globalData.goodsInfo,
        cartInfo: app.globalData.cartInfo,
        count: app.globalData.count,
        cartLength: app.globalData.cartInfo.length
      })
      this.totalMoney();
    }
  },
  bindMinus: function (e) {
    var id = e.currentTarget.dataset.id;
    for (var i = 0; i < app.globalData.cartInfo.length; i++) {
      if (id == app.globalData.cartInfo[i].id) {
        if (parseInt(app.globalData.cartInfo[i].cartNum) > 1) {
          app.changeCart(app.globalData._shopId, app.globalData.userInfo.sessionKey, id, 2);
          app.globalData.cartInfo[i].cartNum = parseInt(app.globalData.cartInfo[i].cartNum) - 1;
          this.setData({
            cartInfo: app.globalData.cartInfo,
          })
        }
      }
    }
    this.totalMoney();
  },
  bindPlus: function (e) {
    var id = e.currentTarget.dataset.id;
    for (var i = 0; i < app.globalData.cartInfo.length; i++) {
      if (id == app.globalData.cartInfo[i].id) {
        if (parseInt(app.globalData.cartInfo[i].cartNum) < parseInt(app.globalData.cartInfo[i].goods_num)) {
          app.changeCart(app.globalData._shopId, app.globalData.userInfo.sessionKey, id, 1);
          app.globalData.cartInfo[i].cartNum = parseInt(app.globalData.cartInfo[i].cartNum) + 1;
          this.setData({
            cartInfo: app.globalData.cartInfo
          })
        } else {
          app.showToastNone('已达库存上限', 1000);
        }
      }
    }
    this.totalMoney();
  },
  changeInput: function (e) {
    var value = e.detail.value;
    var id = e.currentTarget.dataset.id;
    for (var i = 0; i < app.globalData.cartInfo.length; i++) {
      if (id == app.globalData.cartInfo[i].id) {
        if (parseInt(value) < 0 || parseInt(value) == 0 || value.replace(/(^\s*)|(\s*$)/g, '') == '') {
          value = app.globalData.cartInfo[i].cartNum = 1;
        } else {
          if (parseInt(value) > app.globalData.cartInfo[i].goods_num) {
            value = app.globalData.cartInfo[i].cartNum = app.globalData.cartInfo[i].goods_num;
          }
        }
        this.setData({
          cartInfo: app.globalData.cartInfo
        })
      }
    }
    app.changeCart(app.globalData._shopId, app.globalData.userInfo.sessionKey, id, 3, value);
    this.totalMoney();
  },
  addCart: function (e) {
    var id = e.currentTarget.dataset.id;
    var goodsInfo = this.data.goodsInfo;
    var a = 1;
    for (var i = 0; i < goodsInfo.length; i++) {
      if (id == goodsInfo[i].id) {
        for (var j = 0; j < app.globalData.cartInfo.length; j++) {
          if (id == app.globalData.cartInfo[j].id) {
            if (parseInt(app.globalData.cartInfo[j].cartNum) == parseInt(goodsInfo[i]['goods_num']) || parseInt(app.globalData.cartInfo[j].cartNum) > parseInt(goodsInfo[i]['goods_num'])) {
              app.showToastNone('已达库存上限', 1000);
              return false
            }
            app.changeCart(app.globalData._shopId, app.globalData.userInfo.sessionKey, id, 1);
            app.globalData.cartInfo[j].cartNum = parseInt(app.globalData.cartInfo[j].cartNum) + 1;
            a = 2;
          }
        }
        if (a == 1) {
          app.changeCart(app.globalData._shopId, app.globalData.userInfo.sessionKey, id, 1);
          var cart = { id: id, cartNum: 1, unit: goodsInfo[j].unit, title: goodsInfo[i].title, goods_bn: goodsInfo[i].goods_bn, pic_4: goodsInfo[i].pic_4, goods_num: goodsInfo[i].goods_num, price: goodsInfo[i].price };
          app.globalData.cartInfo.push(cart);
        }
      }
    }
    this.setData({
      cartLength: app.globalData.cartInfo.length,
      cartInfo: app.globalData.cartInfo
    })
    this.totalMoney();
  },
  delCart: function (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    wx.request({
      url: app.globalData.host + '/cart/delCart',
      data: {
        'goods_id': id,
        'session_key': app.globalData.userInfo.sessionKey
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        let data = res.data
        if (data.code == 2000) {
          for (var i = 0; i < app.globalData.cartInfo.length; i++) {
            if (id == app.globalData.cartInfo[i].id) {
              app.globalData.cartInfo.splice(i, 1)
            }
          }
          that.clearRemove()
          that.setData({
            cartLength: app.globalData.cartInfo.length,
            cartInfo: app.globalData.cartInfo
          })
          that.totalMoney();
        } else {
          wx.showToast({ title: data.msg, icon: 'none', duration: 2000 })
        }
      }
    })
  },

  understock: function () {
    app.showToastNone('暂无库存', 2000);
  },
  toCoupon: function () {
    wx.navigateTo({
      url: '../coupon/coupon'
    })
  },
  isAgress: function () {
    var agree = this.data.agree
    if (agree == 1) {
      this.setData({
        agree: 0
      })
    } else {
      this.setData({
        agree: 1
      })
    }
  },
  totalMoney: function () {
    var cartInfo = app.globalData.cartInfo;
    var money = 0;
    for (var i = 0; i < cartInfo.length; i++) {
      money += parseFloat(cartInfo[i].price * cartInfo[i].cartNum);
    }
    this.setData({
      allMoney: money.toFixed(2)
    })
  },
  orderPay: function () {
    if (this.data.buthidden == true) {
      return false;
    }
    var cartInfo = app.globalData.cartInfo;
    var goodsInfo = app.globalData.goodsInfo;
    var detail = [];
    var that = this;
    if (app.globalData.cartInfo == 0) {
      app.showToastNone('请选择商品', 2000);
      return false;
    }
    if (this.data.agree == 0) {
      app.showToastNone('请勾选【佳品小栈服务协议】!', 2000);
      return false;
    }
    this.setData({
      buthidden: true
    })
    var open_id = app.globalData.userInfo.openId;
    var session_key = app.globalData.userInfo.sessionKey;
    var money = this.data.allMoney;
    var shop_id = app.globalData.shopInfo.id
    for (var i = 0; i < cartInfo.length; i++) {
      var cart = { goods_id: cartInfo[i].id, num: cartInfo[i].cartNum };
      detail.push(cart);
    }
    wx.request({
      url: app.globalData.host + '/wxpay',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: util.json2Form({
        open_id: open_id,
        session_key: session_key,
        shop_id: shop_id,
        money: that.data.allMoney,
        //money: 0.01,
        detail: JSON.stringify(detail)
      }),
      success: function (res) {
        if (res.data.code == 2000) {
          //显示等待、禁用按钮，后台返回错误则将true和false对调一下就是隐藏等待、启用按钮
          that.setData({
            buthidden: true
          })
          var orderId = res.data.data.data.order_id;
          // 发起支付
          wx.requestPayment({
            'timeStamp': res.data.data.data.timeStamp,
            'nonceStr': res.data.data.data.nonceStr,
            'package': res.data.data.data.package,
            'signType': 'MD5',
            'paySign': res.data.data.data.paySign,
            'success': function (res) {
              that.setData({
                buthidden: true
              })
              wx.showToast({
                title: "支付成功",
                duration: 3000
              })
              app.toPay(orderId)
            },
            'fail': function (res) {
              that.setData({
                buthidden: false
              })
              app.showToastNone('支付失败',2000)
            }
          })
        } else {
          //显示等待、禁用按钮，后台返回错误则将true和false对调一下就是隐藏等待、启用按钮
          that.setData({
            buthidden: false
          })
          wx.showToast({ title: res.data.msg, icon: 'none', duration: 2500 })
        }
      }
    })
  },
  goodsDetail: function (e) {
    var goodsId = e.currentTarget.dataset.id;
    app.toGoodsDetail(goodsId);
  },
  scrollstart: function (e) {
    // console.log(e)
    this.setData({
      startX: e.changedTouches[0].clientX,
      // 数组以后添加删除存在

    })
  },
  scrollmove: function (e) {
    let clearIndex = this.data.clearIndex;
    var clearX = e.changedTouches[0].clientX - this.data.startX
    if (clearX > 10) {
      clearIndex[e.currentTarget.dataset.index] = false;
      this.setData({
        clearIndex: clearIndex
      })
    } else if (clearX < 10) {
      clearIndex[e.currentTarget.dataset.index] = true;
      this.setData({
        clearIndex: clearIndex
      })
    }

  },
  clearRemove: function () {
    this.setData({
      clearIndex: []
    })
  },
  agreement: function (e) {
    wx.request({
      url: app.globalData.host + '/order/agreement',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        if (res.data.code == 2000) {
          wx.downloadFile({
            url: app.globalData.host + res.data.data,
            success: function (res) {
              var filePath = res.tempFilePath
              wx.openDocument({
                filePath: filePath,
                success: function (res) {
                  //console.log('打开文档成功')
                },
                fail: function (err) {
                  wx.showToast({
                    title: 'err',
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            }
          })
        }
      }
    })
  },
  // getCartInfo: function (goodsAndNumStr) {
  //   var that = this;
  //   wx.request({
  //     url: app.globalData.host + '/index/cartList',
  //     method: "POST",
  //     data: { goods_id_num_str: goodsAndNumStr, shop_id: app.globalData._shopId},
  //     header: {
  //       "Content-Type": "application/x-www-form-urlencoded"
  //     },
  //     success: function (res) {
  //       let data = res.data
  //       if (data.code == 2000) {
  //         that.setData({
  //           cartInfo:data.data
  //         })
  //       } else {
  //         app.showToastNone(data.msg);
  //       }
  //     }
  //   })
  // },

  // bindMinus: function (e) {
  //   var key = e.currentTarget.id;
  //   var id = e.currentTarget.dataset.id;
  //   var cartNum = this.data.cartInfo[key].cartNum;
  //   var newarry = this.data.newarry;
  //   if (newarry[key] == undefined){
  //     if (cartNum == 1) {
  //       return false;
  //     }
  //     --cartNum;
  //     newarry[key] = cartNum;
  //   }else{
  //     if (newarry[key] == 1){
  //       return false;
  //     }
  //     --newarry[key];
  //   }
  //   this.setData({
  //     newarry: newarry,
  //   })
  //   this.modefyCartInfo(id)
  // },
  // bindPlus: function (e) {
  //   var key = e.currentTarget.id;
  //   var id = e.currentTarget.dataset.id;
  //   var cartNum = this.data.cartInfo[key].cartNum;
  //   var goodsNum = this.data.cartInfo[key].goods_num;
  //   var newarry = this.data.newarry;
  //   if (newarry[key] == undefined) {
  //     if (cartNum == goodsNum || cartNum > goodsNum) {
  //       app.showToastNone('库存不足');
  //       return false;
  //     }
  //     cartNum ++;
  //     newarry[key] = cartNum;
  //   } else {
  //     if (newarry[key] == goodsNum || newarry[key] > goodsNum) {
  //       app.showToastNone('库存不足');
  //       return false;
  //     }
  //     newarry[key]++;
  //   }
  //   this.setData({
  //     newarry: newarry,
  //   })
  //   this.modefyCartInfo(id)
  // },
  // changeInput: function (e) {
  //   var key = e.currentTarget.id;
  //   var value = e.detail.value;
  //   var id = e.currentTarget.dataset.id;
  //   var newarry = this.data.newarry;
  //   var goodsNum = this.data.cartInfo[key].goods_num;
  //   newarry[key] = parseInt(value.replace(/[^\d]/g, ''))
  //   this.setData({
  //     newarry: newarry,
  //   })
  //   if (parseInt(value) > parseInt(goodsNum)) {
  //     newarry[key] = goodsNum;
  //     this.setData({
  //       newarry: newarry,
  //     })
  //   }
  //   if (parseInt(value) < 0 || parseInt(value) == 0) {
  //     newarry[key] = 1;
  //     this.setData({
  //       newarry: newarry,
  //     })
  //   }
  //   var y = String(value).indexOf(".") + 1
  //   if (y > 0) {
  //     var num = value.split(".")[0];
  //     if (parseInt(num) > parseInt(goodsNum)) {
  //       newarry[key] = goodsNum;
  //       this.setData({
  //         newarry: newarry,
  //       })
  //     } else if(parseInt(num) < 0 || parseInt(num) == 0){
  //       newarry[key] = 1;
  //       this.setData({
  //         newarry: newarry,
  //       })
  //     }else{
  //       newarry[key] = num;
  //       this.setData({
  //         newarry: newarry,
  //       })
  //     }
  //   } 
  //   this.modefyCartInfo(id, newarry[key])
  // },
  // modefyCartInfo: function(id) {
  //   for (var i = 0; i < app.globalData.cartInfo.length; i++) {
  //     if (id == app.globalData.cartInfo[i].id) {
  //       if (app.globalData.cartInfo[i].cartNum > 1) {
  //         app.globalData.cartInfo[i].cartNum = app.globalData.cartInfo[i].cartNum - 1;
  //       }
  //     }
  //   }
  // }
})